import { Index, Token } from "../../../dbserve";
import { rules } from '../../../utils/rules';
import md5 from 'md5';
import config from '../../../config';
import getTree from "../../../utils/toTree";
const list = {
  sex: { type: String, required: false },
  phone: { type: String, required: false },
  email: { type: String, required: false },
  age: { type: String, required: false },
  idCard: { type: String, required: false },
  roles: { type: Array, required: false, default: () => [] },
  superAdmin: { type: Boolean, default: false },
  avatar: { type: String, default: false },
}
const addlist = {
  username: { type: String, required: true },
  password: { type: String, required: true },
  ...list
}
const editlist = {
  id: { required: true },
  ...list
}
const TOKEN = new Token('token');
const RoleGroup = new Index('roleGroup');
const Role = new Index('role');
export default class User extends Index {
  constructor() {
    super('user')
  }
  // 添加用户
  async add(req?: any, res?: any) {
    try {
      const { data, message, error } = rules(req.body, addlist);
      if (error) throw message;
      const { username, password } = data;
      const num = await this._count({ username });
      if (num) throw '账号已存在';
      const bool = await this._add(data);
      if (bool) res.success(bool, '添加成功');
      else throw '添加失败';
    } catch (error) {
      res.msg(error, 400);
    }
  }
  // 修改用户
  async edit(req?: any, res?: any) {
    try {
      const { data, message, error } = rules(req.body, editlist);
      if (error) throw message;
      if (!(await this._count({ id: data.id - 0 }))) throw '用户不存在';
      delete data.username;
      const bool = await this._edit(data);
      if (bool) res.success(bool, '更新成功');
      else throw '更新失败';
    } catch (error) {
      res.msg(error, 400);
    }
  }
  // 删除 
  async del(req?: any, res?: any) {
    try {
      let { id } = req.body;
      if (typeof id === 'number' && id) id = [id];
      if (!id || !id.length) throw '删除的用户id不能为空';
      let userinfo: any = await this._find({ id: { $in: id } });
      if (!userinfo.length) throw '目标不存在';
      if (userinfo.some((e: any) => e.superAdmin)) throw '不能删除超级管理员';
      const bool = await this._del(id);
      if (bool) res.success(bool, '删除成功');
      else throw '删除失败';
    } catch (error) {
      res.msg(error, 400);
    }
  }
  // 获取列表
  async list(req?: any, res?: any) {
    try {
      let { page = 1, size = 0, ...query } = req.query;
      delete query.total;
      const data: any = await this._query({ page: { page, size }, query });
      let list = data.data;
      let arr = [];
      for (let index = 0; index < list.length; index++) {
        let element = list[index];
        delete element.password;
        let data = await RoleGroup._find({ id: { $in: element.roles || [] } });
        element.rolesName = data.map((e: any) => e.name);
        arr.push(element);
      }
      data.data = arr
      res.success(data)
    } catch (error) {
      console.log(error);

      res.msg(error, 400);
    }
  }
  // 登录
  async login(req?: any, res?: any) {
    try {
      let { username = '', password } = req.body;
      if (!username || !password) throw '用户名或密码不能为空';
      let data = await this._find({ username, password });
      if (!data.length) throw '用户名或密码错误';
      // 用户信息
      let userinfo: any = data[0];
      // 用户权限组
      let roleGroups: Array<object | any>
      // 用户所有权限id
      let roleIdArr: Array<number> = []
      // 权限列表
      let roleArr: Array<object | any>;
      // 权限code列表
      let roles: Array<string>;
      // 菜单树
      let menu: Array<any>;
      if (userinfo.superAdmin) {
        // 超级管理员，拥有所有权限
        roleArr = await Role._find({});
      } else {
        // 查询账号下所有用户组包含的权限
        roleGroups = await RoleGroup._find({ id: { $in: userinfo.roles || [] } });
        roleGroups.forEach(e => roleIdArr.push(...e.roles));
        // 权限去重
        roleIdArr = [...new Set(roleIdArr)];
        // 查询权限表获取所有权限
        roleArr = await Role._find({ id: { $in: roleIdArr } });
      }
      // 树形菜单数据
      menu = getTree('', roleArr.filter(e => e.type == 1));
      // 后端验证接口权限，通过path路径匹配
      roleArr = roleArr.filter(e => e.type === 2);
      // 前端接口权限，通过自定义code匹配
      roles = roleArr.map(e => e.code);
      // 生成唯一token
      const token = md5(username + Date.now() + password + Date.now());
      // 清除当前用户的历史token
      await TOKEN._clearToken(username);
      // 存储当前用户数据
      await TOKEN._setToken({ token, maxAge: config.maxAge * 1000 + Date.now(), username, roles: roleArr, superAdmin: userinfo.superAdmin, });
      // 返回登录成功信息
      res.success({ token, maxAge: config.maxAge, menu, userinfo: { ...userinfo, roles } }, '登录成功', 200);
    } catch (error) {
      console.log(error);
      res.msg(error, 400)
    }

  }
  // 退出登录
  async logout(req?: any, res?: any) {
    try {
      const { token } = req.headers;
      if (!token) throw '未查找到用户';
      const bool = await TOKEN._clearToken(token);
      if (bool) res.msg('退出成功')
      else throw '退出失败'
    } catch (error) {
      res.msg(error, 401)
    }
  }
  // 用户组
  async groupList(req: any, res: any) {
    try {
      const { page = 1, size = 0, ...query } = req.query;
      const data = await RoleGroup._query({ page: { page, size }, query });
      res.success(data)
    } catch (error) {
      res.msg(error, 400);
    }
  }
}


